﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gtkj.CMS.Common
{
    public class ReflectHelp
    {
        /// <summary>
        /// 给对象赋值
        /// </summary>
        /// <typeparam name="M">类型</typeparam>
        /// <param name="m">对象</param>
        /// <param name="Request">值</param>
        public static void SetModelValue<M>(M m, System.Web.HttpRequestBase Request)
        {
            int r;
            double u;
            DateTime d;
            decimal e;
            Type T = typeof(M);
            foreach (var i in T.GetProperties())
            {
                string value = Request[i.Name];
                switch (i.PropertyType.Name.ToString().ToLower())
                {
                    case "string":
                        {
                            if (string.IsNullOrWhiteSpace(value))
                                continue;
                            i.SetValue(m, value); break;
                        }
                    case "int32":
                        {
                            if (int.TryParse(value, out r))
                                i.SetValue(m, r);
                            break;
                        }
                    case "double":
                        {
                            if (double.TryParse(value, out u))
                                i.SetValue(m, u);
                            break;
                        }
                    case "datetime":
                        {
                            if (DateTime.TryParse(value, out d))
                                i.SetValue(m, d);
                            break;
                        }
                    case "decimal":
                        {
                            if (decimal.TryParse(value, out e))
                                i.SetValue(m, e);
                            break;
                        }
                    case "boolean":
                        {
                            if (int.TryParse(value, out r))
                            {
                                if (r > 0)
                                {
                                    i.SetValue(m, true);
                                }
                                else
                                {
                                    i.SetValue(m, false);
                                }
                            }
                                
                            break;
                        }
                    default:
                        {
                            if (DateTime.TryParse(value, out d))
                                i.SetValue(m, d);
                            
                            break;
                        }

                }

            }
        }
    }
}
